import GameConfig from "../GameConfig";
import DebugExt from "../NRLib/base/DebugExt";
import ZegoEvents from "./ZegoEvents";

const { ccclass, property } = cc._decorator;
/**
 * 通用頂部玩家信息欄（第三版--紫色版）
 * @export
 * @class GlobalInfoBar
 * @extends {cc.Component}
 */
@ccclass
export default class GlobalInfoBar extends cc.Component implements yy.IPublicUI {

    /// 中央区域
    @property(cc.Sprite)
    private readonly avatar: cc.Sprite = null;
    @property(cc.Label)
    private readonly txtName: cc.Label = null;

    /// 右侧区域
    // 右侧占位容器(由具体游戏传递内容填充，并覆盖原先设置按钮显示区域)
    @property(cc.Node)
    private readonly rightNode: cc.Node = null;
    // 设置按钮
    @property(cc.Button)
    private readonly btnSetting: cc.Button = null;
    // btnHelp(右侧)
    @property(cc.Button)
    private readonly btnHelp2: cc.Button = null;

    // 声音开关
    @property(cc.Button)
    private readonly btnSound: cc.Button = null;
    @property(cc.Node)
    private readonly soundOn: cc.Node = null;

    /// 左侧区域面板
    // 左侧占位容器(由具体游戏传递内容填充，并覆盖原先设置按钮显示区域)
    @property(cc.Node)
    private readonly leftNode: cc.Node = null;
    // 菜单按钮
    @property(cc.Button)
    private readonly btnMenu: cc.Button = null;
    // btnExit(左侧)
    @property(cc.Button)
    private readonly btnExit2: cc.Button = null;
    // layerMenu
    @property(cc.Node)
    private layerMenu: cc.Node = null;
    // btnHelp
    @property(cc.Button)
    private btnHelp: cc.Button = null;
    // btnExit
    @property(cc.Button)
    private btnExit: cc.Button = null;

    // 金币信息按钮节点
    @property(cc.Button)
    private readonly btnCoin: cc.Button = null;
    // 金币文本
    @property(cc.Label)
    private readonly textCoin: cc.Label = null;
    // 金币图标
    @property(cc.Node)
    private readonly iconCoin: cc.Node = null;


    // LIFE-CYCLE CALLBACKS:

    getNode(): cc.Node {
        return this.node;
    }

    private get isNodeValid(): boolean {
        return !!this.node && this.node.isValid;
    }

    onLoad() {
        GlobalInfoBar.ins = this;
        // 初始化中央区域
        this.updatePlayerInfo();
        // 初始化右侧面板
        this.initRightPanel();
        // 初始化左侧面板
        this.initLeftPanel();

        // 监听各种事件
        yy.myself.on(this, yy.event.player.MoneyChanged, this.updateCoins);
        yy.event.on(this, yy.event.lobby.LoginLobbyResult, this.uiResresh);
        yy.event.on(this, yy.event.lobby.LoginAgainResult, this.uiResresh);
        yy.event.on(this, yy.event.CustomEvent, this.onCustomEvent);
        if (this.btnSound)
            yy.event.on(this, yy.event.sys.SettingChanged, this.updateSoundToggle);
    }
    static ins = null;

    onDestroy() {
        if (this.btnSound)
            yy.event.off(yy.event.sys.SettingChanged, this.updateSoundToggle);
        yy.event.off(yy.event.CustomEvent, this.onCustomEvent);
        yy.myself.off(yy.event.player.MoneyChanged, this.updateCoins);
        yy.event.off(yy.event.lobby.LoginLobbyResult, this.uiResresh);
        yy.event.off(yy.event.lobby.LoginAgainResult, this.uiResresh);
    }

    protected onEnable(): void {
        yy.callNextFrame(() => {
            this.uiResresh();
        }, this);
    }

    private uiResresh() {
        // 刷新UI
        this.updateCoins();
        this.updatePlayerInfo();
    }

    private onCustomEvent(evt: yy.event.CustomEvent) {
        if (evt.eventID == "GetCoinLabelPosition") {
            if (this.iconCoin && this.iconCoin.isValid) {
                let worldPos = this.iconCoin.convertToWorldSpaceAR(cc.v2(0, 0));
                let e = new yy.event.CustomEvent();
                e.eventID = "GetCoinLabelPositionResult";
                e.param = worldPos;
                yy.event.emit(yy.event.CustomEvent, e);
            }
        }
        else if (evt.eventID == "updateThridMoney") {
            if (this.isSingleCoinGame()) {
                const moneyType = GameConfig.getCoinID();
                this.updateCoinLabel(evt.param, moneyType);
            }
        }
    }

    /** 判断是否是单币游戏 */
    private isSingleCoinGame(): boolean {
        return "isSingleCoinGame" in GameConfig && GameConfig.isSingleCoinGame() || false;
    }

    //////////////////////////////////   中央区域   /////////////////////////////////////////////////////

    /**
     * 更新中央区域按钮组状态
     * 改为显示玩家信息
     */
    public updatePlayerInfo() {
        if (this.avatar)
            yy.faceCenter.bindUserFace(this.avatar, yy.myself.userID);
        if (this.txtName)
            this.txtName.string = yy.myself.name;
    }

    //////////////////////////////////   右侧区域   /////////////////////////////////////////////////////
    /**
     * 初始化右侧面板区域
     */
    private initRightPanel() {
        // setting
        // this.btnSetting.node.targetOff(this);
        // this.btnSetting.node.on("click", this.onBtnClickedSetting, this);
        this.btnSetting.node.active = false;

        // 声音开关
        if (this.btnSound) {
            this.btnSound.node.on("click", this.onToggleClickedSound, this);
            this.updateSoundToggle();
        }
    }

    // on setting button clicked
    private onBtnClickedSetting() {
        // show setting layer
        // UIPrefabCom.showUI(GlobalLayer_T.SettingLayer_42);
    }

    //////////////////////////////////   左侧区域   /////////////////////////////////////////////////////
    /**
     * 初始化左侧区域面板
     */
    private initLeftPanel() {
        // 初始化左侧区域面板
        // 菜单按钮事件
        // this.btnMenu.node.targetOff(this);
        // this.btnMenu.node.on("click", this.onBtnClickMenu, this);
        this.btnMenu.node.active = false;
        // 金币条点击事件
        this.btnCoin.node.targetOff(this);
        this.btnCoin.interactable = true;
        this.btnCoin.node.on("click", this.onBtnClickCoin, this);
        // 左侧退出按钮是否显示状态更新
        if (this.btnExit2)
            this.btnExit2.node.active = this.showExit;
    }

    private onBtnClickCoin() {
        const e: yy.event.CustomEvent = new yy.event.CustomEvent();
        e.eventID = "EVENT_CLICK_COINS_OPEN_SHOP";
        yy.event.emit(yy.event.CustomEvent, e);
    }

    /**
     * 刷新金币
     */
    private updateCoins() {
        if (!this || !this.isNodeValid || yy.myself.userID == 0 || this.isStopRefreshCoin || this.isSingleCoinGame()) return;
        const moneyType = GameConfig.getCoinID();
        const coinCount = GameConfig.isSingleCoinGame() ? this._realCoinCount : yy.myself.getBodyMoney(moneyType);
        this.updateCoinLabel(coinCount, moneyType);
    }
    /** 更新货币文本 */
    private updateCoinLabel(coinCount: number, moneyType: number) {
        if (coinCount < 0) return;
        this._realCoinCount = coinCount;
        if (!!this.textCoin && this.textCoin.isValid && !this.isCoinLock) {
            this.textCoin.string = yy.gf.formatCoin({
                moneyType,
                coinCount,
                decimalCount: -2,
            });
        }
        // 设置节点可见
        this.node.active = true;
    }
    // 实际货币数量
    private _realCoinCount: number = 0;

    /**
     * 锁定金币资源变化
     * @param dt 锁定时长,默认15秒
     */
    static lockCoin(dt: number = 15) {
        const that = GlobalInfoBar.ins;
        if (!that || !that.isNodeValid) return;
        that.isCoinLock = true;
        that.unscheduleAllCallbacks();
        that.scheduleOnce(() => {
            const ins = GlobalInfoBar.ins;
            if (!ins || !ins.isNodeValid) ins.isCoinLock = true;
        }, dt);
    }
    private isCoinLock: boolean = false;
    /**
     * 解锁金币资源变化
     */
    static unlockCoin() {
        const that = GlobalInfoBar.ins;
        if (!that || !that.isNodeValid) return;
        that.unscheduleAllCallbacks();
        that.isCoinLock = false;
        that.updateCoins();
    }

    // 是否停止自动更新金币数值
    private isStopRefreshCoin: boolean = false;
    // 获取指定组件
    public getElement(type?: any): any {
        DebugExt.log("获取顶部信息栏组件：", type);
        if (!type) return null;
        const uiType: string = type && type.uiType ? (type.uiType as string) || "" : "";
        if (!uiType || uiType.length == 0) return null;

        if (uiType.toLowerCase() == "CoinLabel".toLowerCase()) {
            // 返回金币文本
            this.isStopRefreshCoin = type.isStopRefreshCoin || false;
            return this.textCoin;
        }
        else if (uiType.toLowerCase() == "CoinIcon".toLowerCase()) {
            // 返回金币图标
            return this.iconCoin;
        }
        else if (uiType.toLowerCase() == "GlobalInfoBar".toLowerCase()) {
            //  返回组件对象，用于调用组件内方法
            return this;
        }
        return null;
    }

    /**
     * 初始化子控件
     */
    public init(left: cc.Node, right: cc.Node) {
        // // 初始化隐藏菜单
        // this.layerMenu.active = false;
        // // 检查左侧是否有自定义节点
        // const hasLeftDesign: boolean = left && left.isValid;
        // // left side 和 btnMenu 互斥
        // this.btnMenu.node.active = !hasLeftDesign;
        // if (this.leftNode) {
        //     this.leftNode.removeAllChildren(true);
        //     this.leftNode.active = hasLeftDesign;
        //     if (hasLeftDesign) {
        //         left.parent = this.leftNode;
        //         left.setPosition(cc.Vec2.ZERO);
        //     }
        // }
        // // 检查右侧是否有自定义节点
        // const hasRightDesign: boolean = right && right.isValid;
        // // right side 和 btnSetting 互斥
        // this.btnSetting.node.active = !hasRightDesign;
        // if (this.rightNode) {
        //     this.rightNode.removeAllChildren(true);
        //     this.rightNode.active = hasRightDesign;
        //     if (hasRightDesign) {
        //         right.parent = this.rightNode;
        //         right.setPosition(cc.Vec2.ZERO);
        //     }
        // }
    }

    // 设置menu菜单中的按钮事件(帮助和退出有两组)
    public setMenuBtnEvent(eventHelp: () => void, eventExit: () => void) {
        // 帮助按钮事件，不传值不显示该按钮
        if (this.btnHelp2) {
            this.btnHelp2.node.active = !!eventHelp;
            if (eventHelp)
                this.btnHelp2.node.on("click", () => {
                    // this.layerMenu.active = false;
                    eventHelp();
                });
        }
        // 退出按钮事件，不传值调用默认退出
        if (this.btnExit2 && this.showExit) {
            this.btnExit2.node.active = true;
            this.btnExit2.node.on("click", () => {
                // this.layerMenu.active = false;
                // zego 退出按钮点击 打点
                if (GameConfig.isZEGO) {
                    // 退出游戏，当做游戏状态结束
                    if (!!ZegoEvents.gamePhasePlayEnd)
                        ZegoEvents.gamePhasePlayEnd();

                    // 需求：回调需要加开关，默认关，配置了才开
                    let sendEvent = false;
                    const evnCfg = yy.thirdPlatform.getEnvConfigs();
                    if (evnCfg && evnCfg.zego && evnCfg.zego.gameConfig && evnCfg.zego.gameConfig.specificConfig) {
                        const needQuitEvent = evnCfg.zego.gameConfig.specificConfig["needQuitEvent"];
                        if (needQuitEvent !== undefined)
                            sendEvent = needQuitEvent == "1";
                    }
                    DebugExt.debug("zego quit event, 是否发送退出事件：", sendEvent);
                    if (sendEvent) {
                        // 有第三方接管，不执行后续逻辑
                        yy.thirdPlatform.onAction(yy.ThirdActionType.Quit);
                        return;
                    }
                }

                if (eventExit)
                    eventExit();
                else
                    ZegoEvents.exitGame();
            });
        }
    }

    // 点击menu
    private onBtnClickMenu() {
        this.layerMenu.active = !this.layerMenu.active;
    }

    // zego渠道自定义配置是否显示退出按钮--默认显示
    private get showExit(): boolean {
        let visible = true;
        if (GameConfig.isZEGO) {
            const cfg = yy.thirdPlatform.getEnvConfigs();
            if (cfg && cfg.zego && cfg.zego.gameConfig && cfg.zego.gameConfig.specificConfig) {
                const spCfg = cfg.zego.gameConfig.specificConfig;
                if (spCfg.showExit !== undefined)
                    visible = spCfg.showExit == "1";
            }
        }
        return visible;
    }

    private onToggleClickedSound() {
        const isMute = yy.setting.isMute;
        yy.setting.isMute = !isMute;
    }
    private updateSoundToggle() {
        if (!this.soundOn) return;
        const isMute = yy.setting.isMute;
        this.soundOn.active = !isMute;
    }
}
